<template>
  <Drawer :title="title"
          :mask="false"
          closable
          :width="width"
          :value="visible"
          @on-visible-change="onChangeVisible">
    <div class="topbar-search m-b-10">
      <div class="flex a-center j-between">
        <div class="flex">
          <MyTreeSelect :value="name"
                        placeholder="姓名"
                        clearable
                        class="m-r-10"
                        style="width: 160px"
                        :data="personTreeArr"
                        search
                        checked
                        @onCheckChange="onChangeName"></MyTreeSelect>
        </div>
        <div class="flex">
          <Button type="primary"
                  class="m-l-10"
                  @click.stop="onClickSearch">
            <Icon custom="i-icon icon-sousuo"
                  size="16"></Icon>
            查询
          </Button>
          <Button class="m-l-10"
                  @click.stop="onClickReset">
            <Icon custom="i-icon icon-shuaxin"
                  size="16"></Icon>
            重置
          </Button>
        </div>
      </div>
    </div>
    <Table ref="table"
           :height="tableHeight"
           :columns="columnsPlan"
           :data="data"
           border
           stripe
           :loading="tableLoading"
           @on-selection-change="onChangeSelect">
      <template slot-scope="{ row }"
                slot="operation">
        <!-- <Button type="text"
                class="tableOperaBtn"
                @click.stop="onClickEditPlan(row)">修改</Button> -->
        <Button type="text"
                class="tableOperaBtn"
                @click.stop="onClickClearPlan(row)">清空</Button>
      </template>
    </Table>
    <Page class="m-t-10 m-l-10"
          :total="totalPage"
          :current="pageNum"
          :page-size="pageSize"
          show-total
          show-sizer
          show-elevator
          @on-change="onPageChange"
          @on-page-size-change="onPageSizeChange" />

    <!-- 添加班组 -->
    <RoadCleanShiftGroupModal v-model="roadCleanShiftGroupVisible"
                              @onClickConfirm="onClickGroupConfirm"></RoadCleanShiftGroupModal>

    <!-- 修改排班 -->
    <RoadCleanShiftModal v-model="roadCleanShiftVisible"
                         :data="tableClickDay"
                         @onClickEditGroup="onClickPlanEditGroup"
                         @onClickHoliday="onClickPlanEditHoliday"></RoadCleanShiftModal>
  </Drawer>
</template>

<script>
import {
  getCurrentMonth,
  getNextMonth,
  getMonthDays,
} from "@/utils/dateRangUtil";
import RoadCleanShiftGroupModal from "@/components/product/admin/modal/work/RoadCleanShiftGroupModal";
import RoadCleanShiftModal from "@/components/product/admin/modal/work/RoadCleanShiftModal";
import { mapActions, mapGetters } from "vuex";
import MyTreeSelect from "@/components/common/MyTreeSelect";
export default {
  components: {
    RoadCleanShiftGroupModal,
    RoadCleanShiftModal,
    MyTreeSelect,
  },
  model: {
    prop: "visible",
    event: "onChange",
  },
  props: {
    visible: Boolean,
    title: String,
    width: Number,
    dataId: String,
    date: String,
  },
  data () {
    return {
      name: "",
      nameId: "",
      height: 0,
      summerTime: "",
      winterTime: "",
      totalPage: 0,
      pageNum: 1,
      pageSize: 20,
      tableWidth: 0,
      tableHeight: 0,
      tableLoading: false,
      columnsPlan: [
        {
          type: "selection",
          width: 45,
          fixed: "left",
          align: "center",
        },
        {
          title: "序号",
          width: 45,
          fixed: "left",
          align: "center",
          render: (h, params) => {
            let index = params.index + 1;
            let num = (this.pageNum - 1) * this.pageSize + index;
            return h("span", num);
          },
        },
        {
          title: "姓名",
          key: "employeeName",
          width: 70,
          tooltip: true,
          fixed: "left",
          align: "center",
        },
        {
          title: "所属部门",
          key: "departmentName",
          width: 110,
          tooltip: true,
          fixed: "left",
          align: "center",
        },
        {
          title: "操作",
          slot: "operation",
          width: 90,
          fixed: "right",
          align: "center",
        },
      ],
      data: [],
      // 添加班组
      roadCleanShiftGroupVisible: false,
      // 修改排班
      roadCleanShiftVisible: false,
      roadCleanShiftData: {},
      // 表格中点击添加班组时的日期
      tableClickDay: {},
    };
  },
  watch: {
    visible (newVal) {
      if (newVal) {
        this.init();
      } else {
        this.$emit("onClickCancel");
      }
    },
    dataId (newValue) {
      newValue && this.getDetail();
    },
  },
  computed: {
    ...mapGetters({
      personTreeArr: "getPersonTreeList",
    }),
  },
  mounted () {
    this.height = window.innerHeight - 160;
  },
  methods: {
    ...mapActions(["updatePersonTreeList"]),
    init () {
      this.getTimeDetail();
      this.updatePersonTreeList();
      this.tableHeight = window.innerHeight - 220;
    },
    getDetail () {
      let params = {
        page: this.pageNum,
        size: this.pageSize,
        planId: this.dataId,
        employeeList: this.nameId ? this.nameId.split(',') : []
      };
      this.dateColumnInit();
      this.tableLoading = true;
      this.$http.getRoadPlanDetailListNew(params).then((res) => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.totalPage = res.result.total;
          this.data = res.result.list;
        }
      }).catch((err) => {
        this.tableLoading = false;
      });
    },
    // 修改姓名
    onChangeName (section) {
      let idArr = [];
      let valueArr = [];
      section.forEach((item) => {
        if (item.type === "user") {
          idArr.push(item.id);
          valueArr.push(item.name);
        }
      });
      this.nameId = idArr.join();
      this.name = valueArr.join();
    },
    onChangeSelect (selection) {
      this.selectArr = selection.map((item) => item.id);
    },
    // 页数改变
    onPageChange (event) {
      this.pageNum = event;
      this.getDetail();
    },
    // 每页条数改变
    onPageSizeChange (event) {
      this.pageSize = event;
      this.getDetail();
    },
    // 获取冬夏时间详情
    getTimeDetail () {
      this.$store.dispatch("getTimeCompleteDetail", 2).then((res) => {
        let summer = res.summerDate.split("-");
        this.summerTime = summer[0] + "月" + summer[1] + "日";
        let winter = res.winterDate.split("-");
        this.winterTime = winter[0] + "月" + winter[1] + "日";
      });
    },
    // 初始化table日期列
    dateColumnInit () {
      let year = this.date.substring(0, 4);
      let month = this.date.substring(5, 7);
      let today = new Date().getDate();
      let dayCount = getMonthDays(year, parseInt(month) - 1);
      let dateArr = [];
      for (let i = 1; i <= dayCount; i++) {
        let day = i;
        if (day < 10) {
          day = "0" + day;
        }
        dateArr.push({
          title: month + "/" + day,
          key: year + "-" + month + "-" + day,
          width: 140,
          align: "center",
          render: (h, params) => {
            let row = params.row;
            let column = params.column;
            let currentDateItem = this.getCurrentDateItem(column.key, row.empPlanDetailVoList);
            let isBeyondDate = new Date() >= new Date(column.key);
            let content;
            if (currentDateItem) {
              // 有排班
              if (currentDateItem.workGroupId == "0") {
                // 休假
                content = h(
                  "div",
                  {
                    style: {
                      cursor: isBeyondDate ? "" : "pointer",
                    },
                  },
                  [
                    h("Icon", {
                      attrs: {
                        custom: "i-icon icon-xiu",
                        size: "26",
                        color: "#0eb36e",
                      },
                    }),
                  ]
                );
              } else {
                // 班组
                content = h(
                  "div",
                  {
                    style: {
                      lineHeight: "32px",
                      cursor: isBeyondDate ? "" : "pointer",
                    },
                    on: {
                      click: () => { !isBeyondDate && this.onClickPlanDay(column, row, currentDateItem) },
                    },
                  },
                  [
                    currentDateItem.workKaoQinList.map((item) => {
                      let type = currentDateItem.kaoQinType;
                      let text = "";
                      if (type === 1) {
                        text = `${item.name}(${item.sbsj}~${item.xbsj})`;
                      } else {
                        let date = new Date(year, month, day);
                        let summerDate = new Date(
                          year,
                          this.summerTime.substring(0, 2),
                          this.summerTime.substring(3, 5)
                        );
                        let winterDate = new Date(
                          year,
                          this.winterTime.substring(0, 2),
                          this.winterTime.substring(3, 5)
                        );
                        if (date >= summerDate && date < winterDate) {
                          // 夏季
                          text = `${item.name}(${item.xsbsj}~${item.xxbsj})`;
                        } else {
                          // 冬季
                          text = `${item.name}(${item.dsbsj}~${item.dxbsj})`;
                        }
                      }
                      return h("p", text);
                    }),
                  ]
                );
              }
            } else {
              // 没有排班
              content = h("div", [
                h("p", "该计划下暂无排班"),
                !isBeyondDate &&
                h(
                  "div",
                  {
                    style: {
                      display: "flex",
                      alignItems: "center",
                      marginTop: "10px",
                    },
                  },
                  [
                    h(
                      "Button",
                      {
                        attrs: {
                          type: "text",
                        },
                        style: {
                          color: "#25bb96",
                          padding: "0 5px",
                          height: "22px",
                          fontSize: "12px",
                          lineHeight: "1",
                        },
                        on: {
                          click: () => {
                            this.onClickPlanAddGroup(column, row);
                          },
                        },
                      },
                      [
                        h("Icon", {
                          attrs: {
                            custom: "i-icon icon-tianjiabiankuang",
                            size: "16",
                          },
                        }),
                        h("span", "添加班组"),
                      ]
                    ),
                    h(
                      "Button",
                      {
                        attrs: {
                          type: "text",
                        },
                        style: {
                          color: "#25bb96",
                          padding: "0 5px",
                          height: "22px",
                          fontSize: "12px",
                          lineHeight: "1",
                        },
                        on: {
                          click: () => {
                            this.onClickPlanHoliday(column, row);
                          },
                        },
                      }
                      //  [
                      //   h('Icon', {
                      //     attrs: {
                      //       custom: 'i-icon icon-shijian',
                      //       size: '16'
                      //     }
                      //   }),
                      //   h('span', '休假')
                      // ]
                    ),
                  ]
                ),
              ]);
            }
            return h(
              "div",
              {
                style: {
                  height: "64px",
                  textAlign: "center",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: "12px",
                },
              },
              [content]
            );
          },
        });
      }
      this.columnsPlan.splice(3, this.columnsPlan.length - 5, ...dateArr);
    },
    // 获取当前日期item
    getCurrentDateItem (date, arr) {
      let str;
      if (arr && arr.length != 0) {
        str = arr.find((item) => item.date === date);
      }
      return str;
    },
    // 点击table添加班组
    onClickPlanAddGroup (column, row) {
      this.tableClickDay = {
        id: row.workPlanId,
        personId: row.employeeId,
        date: column.key,
        gridId: row.gridId,
      };
      this.roadCleanShiftGroupVisible = true;
    },
    // 点击table修改班组
    onClickPlanEditGroup () {
      this.roadCleanShiftGroupVisible = true;
    },
    // 添加班组 确认回调
    onClickGroupConfirm (group) {
      let params = {}
      // if (this.tableClickDay.dayId) {
      //   // 修改
      //   let params = {
      //     empPlanDateIdList: [this.tableClickDay.dayId],
      //     workGroupId: group.id,
      //   }
      //   this.$http.createRoadPlanDayNew(params).then((result) => {
      //     this.getDetail()
      //     this.tableClickDay = {}
      //   })
      // } else {
      // 新增
      if (this.tableClickDay.empPlanWorkGroupId) {
        params.workGroupId = group.id
        params.empPlanWorkGroupId = this.tableClickDay.empPlanWorkGroupId
      } else {
        params = {
          planId: this.dataId,
          employeeId: this.tableClickDay.personId,
          date: this.tableClickDay.date,
          workGroupId: group.id,
        }
      }
      // params = {
      //   planId: this.dataId,
      //   employeeId: this.tableClickDay.personId,
      //   date: this.tableClickDay.date,
      //   workGroupId: group.id,
      // }
      this.$http.createRoadPlanDayNew(params).then((result) => {
        this.getDetail()
        this.tableClickDay = {}
      })
      // }
    },
    // 点击table休假
    onClickPlanHoliday (column, row) {
      // this.$Modal.confirm({
      //   title: '休假',
      //   content: '确认休假?',
      //   onOk: () => {
      //     this.tableClickDay = {
      //       id: row.workPlanId,
      //       personId: row.personId,
      //       date: column.key
      //     }
      //     this.onClickGroupConfirm({ id: 0 })
      //   }
      // })
    },
    // 点击table修改休假
    onClickPlanEditHoliday () {
      // this.$Modal.confirm({
      //   title: '休假',
      //   content: '确认休假?',
      //   onOk: () => {
      //     this.onClickGroupConfirm({ id: 0 })
      //   }
      // })
    },
    // 点击table单天排班
    onClickPlanDay (column, row, currentDateItem) {
      this.tableClickDay = {
        id: row.workPlanId,
        dayId: currentDateItem.empPlanDateId,
        personId: row.employeeId,
        person: row.employeeName,
        date: column.key,
        gridId: row.gridId,
        empPlanWorkGroupId: currentDateItem.empPlanWorkGroupId
      };
      this.tableClickDay.text = currentDateItem.workKaoQinList.map((item) => {
        let type = currentDateItem.kaoQinType;
        let text = "";
        if (type === 1) {
          text = `${item.name}(${item.sbsj}~${item.xbsj})`;
        } else {
          let date = new Date(column.key);
          let summerDate = new Date(
            this.summerTime.substring(0, 2),
            this.summerTime.substring(3, 5)
          );
          let winterDate = new Date(
            this.winterTime.substring(0, 2),
            this.winterTime.substring(3, 5)
          );
          if (date >= summerDate && date < winterDate) {
            // 夏季
            text = `${item.name}(${item.xsbsj}~${item.xxbsj})`;
          } else {
            // 冬季
            text = `${item.name}(${item.dsbsj}~${item.dxbsj})`;
          }
        }
        return text;
      }).join();
      this.roadCleanShiftVisible = true;
    },
    onChangeVisible (boo) {
      if (!boo) {
        this.resetData();
        this.$emit("update:dataId", "");
        this.$emit("update:date", "");
        this.$emit("onChange", false);
      }
    },
    // 查询
    onClickSearch () {
      this.pageNum = 1;
      this.getDetail();
    },
    // 点击重置
    onClickReset () {
      this.resetData();
      this.onClickSearch();
    },
    resetData () {
      this.nameId = "";
      this.name = "";
    },
    // 清空排班计划
    onClickClearPlan (row) {
      let empPlanEmployeeIdList = [];
      let empPlanDateIdList = [];
      row.empPlanDetailVoList.forEach((item) => {
        empPlanEmployeeIdList.push(item.empPlanEmployeeId);
        empPlanDateIdList.push(item.empPlanDateId);
      });
      this.$Modal.confirm({
        title: "清空",
        content: "确认清空?",
        loading: true,
        onOk: () => {
          let params = {
            empPlanEmployeeIdList: empPlanEmployeeIdList,
            empPlanDateIdList: empPlanDateIdList,
          };
          this.$http
            .deleteRoadPlanDayNew(params)
            .then((res) => {
              this.$Message.info(res.message);
              if (res.code === 200) {
                this.getDetail();
                this.$Modal.remove();
              }
            })
            .catch((err) => {
              this.$Modal.remove();
            });
        },
      });
    },
  },
};
</script>

<style lang='scss' scoped>
::v-deep {
  .ivu-drawer {
    top: 60px;
    bottom: 0;
  }
}
</style>